<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card >
      <el-row :gutter="30">
        <el-col :span="6">
          <el-input placeholder="请输入内容" v-model="params.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="userList"
        stripe
        border>
        <el-table-column
          type="index"
        label="#">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名称"
          width="150">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色名称"
          width="150">
        </el-table-column>
        <el-table-column
          prop="mobile"
          width="150px"
          label="电话">
        </el-table-column>
        <el-table-column
          width="120px"
          label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeMgState(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="email"
          width="150px"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="create_time"
          width="150px"
          label="创建时间">
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="openEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUserById(scope.row.id)"></el-button>
            <el-tooltip  effect="dark" content="角色管理" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <el-dialog
      class="wb"
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
      :close-on-click-modal="false">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" status-icon label-width="70px" >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog

      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose">
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" status-icon label-width="70px" >
        <el-form-item label="用户名"  >
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data(){
    var checkEmail = (rule, value, callback) => {
        const rem = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (rem.test(value)) {
          callback();
        } else {
            callback(new Error('请输入正确格式的邮箱'));
        }
    };
    var checkPhone = (rule, value, callback) => {
      const rem = /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/
      if (rem.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确格式的电话号码'));
      }
    };
    return {
      userList: [],
      params: {
        query :'',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      addDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur'},
          { min: 3, max: 10, message: '用户名的长度应该大于3小于10', trigger: 'blur'}
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur'}
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur'},
          { validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur'},
          { validator: checkPhone, trigger: 'blur'}
        ]
      },
      editDialogVisible: false,
      editForm: {}
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList(){
      const { data: res } = await this.$http.get('users',{
        params: this.params
      })
      if(res.meta.status !== 200){
        return this.$message.error("获取用户列表失败")
      }
      this.userList = res.data.users;
      this.total = res.data.total
    },
    handleSizeChange(newSize){
      this.params.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage){
      this.params.pagenum = newPage
      this.getUserList()
    },
    async changeMgState(user){
      const { data:res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`)
      if(res.meta.status !== 200){
        user.mg_state = !user.mg_state;
        return this.$message.error("更新用户状态失败！！！")
      }
      this.$message.success("更新用户状态成功！！！")

    },
    addDialogClose(){
      this.$refs.addFormRef.resetFields()
    },
    addUser(){
      this.$refs.addFormRef.validate( async valid => {
         if(valid){
           const { data:res } = await this.$http.post('users',this.addForm)
           if(res.meta.status !==201){
             this.$message.error("添加用户失败！！！")
           }else {
             this.$message.success("添加用户成功！！！")
             this.addDialogVisible = false
             this.getUserList()
           }
         }
      })
    },
    editDialogClose(){
      this.$refs.editFormRef.resetFields()
    },
    editUser(){
      this.$refs.editFormRef.validate( async valid => {
        if(valid){
          const { data:res } = await this.$http.put('users/'+this.editForm.id,{ email:this.editForm.email,mobile:this.editForm.mobile})
          if(res.meta.status !==200){
            this.$message.error("更新用户失败！！！")
          }else {
            this.$message.success("更新用户成功！！！")
            this.editDialogVisible = false
            this.getUserList()
          }
        }
      })
    },
    async openEditDialog(id){
      const { data: res } = await this.$http.get('users/'+id)
        if(res.meta.status !== 200){
          this.$message.error("获取用户信息失败！！！")
        }else {
          this.editDialogVisible = true
          this.editForm = res.data
        }
    },
    deleteUserById(id){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete("users/"+id)
        if(res.meta.status !== 200){
          this.$message.error("删除用户失败！！！")
        }else{
          this.$message.success("删除用户成功！！！")
          this.getUserList()
        }
      }).catch(() => {
        this.$message.info("已取消删除操作！！！")
      });
    }
  }
}
</script>

<style scoped>

.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 20px;
}
/deep/ .wb .el-dialog__body {
  padding: 0px 0px  !important;
}
</style>
